package com.abocode.aichat.app.vo;

import com.abocode.aichat.app.constant.Constant;
import com.abocode.aichat.app.constant.ErrorCode;
import com.abocode.aichat.app.exception.ContextRuntimeException;
import com.abocode.aichat.app.utils.EncryptionUtils;
import com.abocode.aichat.app.utils.StringUtil;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;

/**
 * Created by guanxf on 2015/12/31.
 */
public class HttpHelper {
    @Value("${auth.token.version}")
    private int tokenVersion;

    @Value("${auth.appids}")
    private String appIds;

    public  AuthorizationVo getAuthorizationVo(HttpServletRequest request) {
        String  authorization=request.getHeader(Constant.AUTHORIZATIONCONSTANT.AUTHORIZATION);//:	*md5(http body)
        String  token=request.getHeader(Constant.AUTHORIZATIONCONSTANT.TOKEN);//:	*md5(http body)
        String  appid =request.getHeader(Constant.AUTHORIZATIONCONSTANT.APPID);;//:	*应用编号（产品ID）
        String  dtype =request.getHeader(Constant.AUTHORIZATIONCONSTANT.DTYPE);//	*设备类型，Android、iOS
        String  imei =request.getHeader(Constant.AUTHORIZATIONCONSTANT.IMEI);//	IMEI
        String  imsi=request.getHeader(Constant.AUTHORIZATIONCONSTANT.IMSI);	//IMSI
        String  version=request.getHeader(Constant.AUTHORIZATIONCONSTANT.VERSION);//	*客户端版本号
        String  apn =request.getHeader(Constant.AUTHORIZATIONCONSTANT.APN);//	网络接入点名称，如uninet，cmnet，uniwap，cmwap，3gwap，3gnet，wifi，ctnet,ctwap(能获取到的必须传，iphone获取不到可为空)
        String  nettype=request.getHeader(Constant.AUTHORIZATIONCONSTANT.NETTYPE);//	网络类型：Wifi、2G、3G、4G
        String  mac =request.getHeader(Constant.AUTHORIZATIONCONSTANT.MAC);//	手机端mac地址
        String  data=request.getHeader(Constant.AUTHORIZATIONCONSTANT.DATA);//:	*md5(http body)

        if(StringUtil.isNullOrWhiteSpace(authorization)){
            throw new ContextRuntimeException(ErrorCode.COMM_PARAMETER_INVALID, String.format("请求参数校验失败,authorization is null"));
        }
        if(StringUtil.isNullOrWhiteSpace(appid)){
            throw new ContextRuntimeException(ErrorCode.COMM_PARAMETER_INVALID, String.format("请求参数校验失败,appid is null"));
        }
        if(StringUtil.isNullOrWhiteSpace(dtype)){
            throw new ContextRuntimeException(ErrorCode.COMM_PARAMETER_INVALID, String.format("请求参数校验失败,dtype is null"));
        }
        if(StringUtil.isNullOrWhiteSpace(version)){
            throw new ContextRuntimeException(ErrorCode.COMM_PARAMETER_INVALID, String.format("请求参数校验失败,version is null"));
        }
        if(StringUtil.isNullOrWhiteSpace(data)){
            throw new ContextRuntimeException(ErrorCode.COMM_PARAMETER_INVALID, String.format("请求参数校验失败,data is null"));
        }
        if(!appIds.contains(appid)){
            throw new ContextRuntimeException(ErrorCode.COMM_PARAMETER_INVALID, String.format("请求参数校验失败,appid %s 不存在",appid));
        }

        AuthorizationVo authorizationVo=new AuthorizationVo();
        authorizationVo.setToken(token);
        authorizationVo.setAppid(appid);
        authorizationVo.setDtype(dtype);
        authorizationVo.setImei(imei);
        authorizationVo.setImsi(imsi);
        authorizationVo.setVersion(version);
//        authorizationVo.setApn(apn);
        try {
            authorizationVo.setApn(URLDecoder.decode(apn, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new ContextRuntimeException(ErrorCode.COMM_PARAMETER_INVALID, String.format("请求参数校验失败,apn is not illegal"));
        }
        authorizationVo.setData(data);
        authorizationVo.setMac(mac);
        authorizationVo.setNettype(nettype);
        authorizationVo.setAuthorization(authorization);
        return  authorizationVo;
    }


    public boolean isExpiredToken(String token) {
        try {
            token = EncryptionUtils.fromDESToBASE64(token);
            String[] tokenchilds=token.split("\\$");
            int version=Integer.valueOf(tokenchilds[2]);
            if(version<tokenVersion){
                return  true;
            }

            String expiredDays=tokenchilds[3];
            long time = Long.parseLong(expiredDays);
            long now = new Date().getTime();
            if(time < now){
                return  true;
            }
        } catch (Exception ex) {
            throw new ContextRuntimeException(ErrorCode.COMM_INVALID_REQUEST, String.format("非法请求,token校验失败"));
        }
        return  false;
    }

    /***
     * 获取请求Body
     * @param request
     * @return
     * @throws Exception
     */

    public  String getRequestBody(HttpServletRequest request) {
        String  body="";
        if(request instanceof RereadHttpServletRequestWrapper ){
            RereadHttpServletRequestWrapper wrapper= (RereadHttpServletRequestWrapper) request;
            body= wrapper.getBody();
        }

        return  body;
    }


    public  boolean checkUri(String uri,String authResources) {
        String[] authResource=authResources.split("$");
        String reg="/.*";
        for (int i=0;i<authResource.length;i++){
            reg=authResource[i]+reg;
            if(uri.matches(reg)){
                return true;
            }
        }
        return false;
    }

    public String getUid(String token) {
        String str="";
        try {
            token = EncryptionUtils.fromDESToBASE64(token);
            String[] tokenchilds=token.split("\\$");
            str =tokenchilds[0];
        } catch (Exception ex) {
            throw new ContextRuntimeException(ErrorCode.COMM_INVALID_REQUEST, String.format("非法请求,token校验失败"));
        }
       return  str;
    }
}
